package panda.client.listeners;

import panda.client.Cardpanda;
import panda.client.ui.widgets.BinExplorer;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.MouseListener;
import com.google.gwt.user.client.ui.Widget;

/**
 * A MouseListener for the top label of a BinExplorer.  Dragging the label enables the entire
 * BinExplorer object to move.
 * @author zane.tian@gmail.com
 */
public class BinExplorerMouseListener implements MouseListener {
	private boolean dragging = false;
	private int xOffset; // position in source widget where mouse is before dragging
	private int yOffset;
	
	private BinExplorer ex;
	
	public BinExplorerMouseListener(BinExplorer ex) {
		this.ex = ex;
	}

	public void onMouseDown(Widget source, int x, int y) {
		ex.addStyleName("mouseStyle-dragging");
		// CanvasLog.get().log("DOWN x:" + x + " y:" + y);

		DOM.setCapture(source.getElement());
		dragging = true;
		xOffset = x;
		yOffset = y;

		// CanvasLog.get().log("shell selected");
	}

	public void onMouseMove(Widget source, int x, int y) {
		/* Not really sure why these constants are necessary =( ah ha! because of canvas's offset coords */
		// final int wtfIsGoingOnX = 10;
		// final int wtfIsGoingOnY = 12;
		
		if(dragging) {
			// CanvasLog.get().log("dragging shell - x:" + x + " y:" + y);

			int xAbs = x + source.getAbsoluteLeft() - Cardpanda.canvas.getAbsoluteLeft();
			int yAbs = y + source.getAbsoluteTop() - Cardpanda.canvas.getAbsoluteTop();
			Cardpanda.canvas.setWidgetPosition(ex, xAbs - xOffset, yAbs - yOffset);
		}
	}

	public void onMouseUp(Widget source, int x, int y) {
		ex.removeStyleName("mouseStyle-dragging");
		DOM.releaseCapture(source.getElement());
		dragging = false;
		
		Cardpanda.clientModel.setSelectedBinEx(ex);
	}

	public void onMouseEnter(Widget sender) {
		ex.addStyleName("mouseStyle-mouseover");
		// CanvasLog.get().log("mouse entered dragmetitle");
	}

	public void onMouseLeave(Widget sender) {
		ex.removeStyleName("mouseStyle-mouseover");
		// CanvasLog.get().log("mouse left dragmetitle");
	}
}